import json
from datetime import datetime
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
import base64
from cryptography.hazmat.primitives import serialization




# 验证授权主函数
def verify_license():
    # 1. 加载公钥（嵌入在代码中）
    PUBLIC_KEY = b"""-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwNSWDWJgWiRNGMO9aoad
7yUZTfiAKOnqxvyD17gxOVUgw25+2HhLOTPWeW0vZx/ba6Q7W65XzAnLVxu0AQxp
JsjKYzAWJDHZ8llxVmRGtBLHdUGHWdfi1xzdSEOdj7LWemvdvrgtvyqT+K0jOu8U
+GRgQC8WsSybBaj3eV4nL4/+ElfT05g7cUEMNlghZbeVM8U9giBeADYGKYWMQ02s
nTJLtkZNEOhllvDSpxnQLAt0CavQGj/5FNJcPd/hj6qnu/uQVvpnBIS8T4aTd7LQ
0kjLs6P0Q0Nr0O/OaZdrEIwOxI2z+E/YqoKOk8kH2FuG/yD9MbdR/XL52SGSJt76
DwIDAQAB
-----END PUBLIC KEY-----
"""

    public_key = serialization.load_pem_public_key(PUBLIC_KEY)

    # 2. 读取授权文件
    try:
        with open("license.lic", "r") as lic_file:
            license_file = json.load(lic_file)
    except:
        return False, "授权文件缺失"

    # 3. 验证签名
    try:
        signature = base64.b64decode(license_file["signature"])
        public_key.verify(
            signature,
            json.dumps(license_file["data"]).encode(),
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
    except:
        return False, "授权签名无效"

    data = license_file["data"]

    # # 4. 检查硬件ID
    # if data["hardware_id"] != get_hardware_id():
    #     return False, "硬件不匹配"

    # 5. 检查有效期
    expiry_date = datetime.strptime(data["expiry_date"], "%Y-%m-%d")
    if datetime.now() > expiry_date:
        return False, "授权已过期"+ f"（有效期至 {data['expiry_date']}）"

    # # 6. 时间篡改检查（可选增强）
    # if "last_run" in data:
    #     last_run = datetime.strptime(data["last_run"], "%Y-%m-%d")
    #     if datetime.now() < last_run:
    #         return False, "系统时间异常"

    return True, f"授权有效至 {data['expiry_date']}"

#
# # 系统启动验证
# if __name__ == "__main__":
#     is_valid, message = verify_license()
#     if not is_valid:
#         print(f"系统启动失败: {message}")
#         exit(1)
#
#     print(f"系统验证通过！{message}")
#     # 此处启动主系统...